package net.xdclass.controller;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.controller.request.wx.NativeOrderRequest;
import net.xdclass.enums.PayOrderType;
import net.xdclass.service.WxPayService;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * @author Administrator
 * @description
 * @since 2023-07-02 14:59
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatPayController {

    @Autowired
    private WxPayService wxPayService;

    /**
     * native 下单接口
     */
    @PostMapping("/v3/pay/transactions/native")
    public JsonData nativeOrder(@RequestBody NativeOrderRequest nativeOrderRequest) {

        Map<String, Object> resultData = wxPayService.insertPrepareOrder(nativeOrderRequest);
        log.info("下单接口返回参数: {}", resultData);

        return JsonData.buildSuccess(resultData);
    }


    /**
     * 订单支付接口
     * @param orderId
     * @return
     */
    @GetMapping("/v3/pay/transactions/pay")
    public JsonData nativePay(Long orderId) {
        if (orderId == null) {
            return JsonData.buildError("参数不完整");
        }

        Boolean result = wxPayService.payByOrderId(orderId);

        return result ? JsonData.buildSuccess() : JsonData.buildError("订单支付失败");
    }

    /**
     * 查询订单状态
     *
     * @param merid
     * @param outTradeNo
     * @return
     */
    @GetMapping("/v3/pay/transactions/status")
    public JsonData queryOrderStatus(@RequestParam("mchid") String merid,
                                     @RequestParam("out_trade_no") String outTradeNo) {
        String status = wxPayService.queryOrderStatusByOutTradeNo(outTradeNo, merid);
        return JsonData.buildSuccess(status);
    }

    /**
     * 关闭订单
     *
     * @param merid
     * @param outTradeNo
     * @return
     */
    @GetMapping("/v3/pay/transactions/close")
    public JsonData closeOrderStatus(@RequestParam("mchid") String merid,
                                     @RequestParam("out_trade_no") String outTradeNo) {
        // 将订单从待支付状态改为超时
        Boolean closeFlag = wxPayService.changeOrderStatusByOutTradeNo(outTradeNo, merid,
                PayOrderType.PREPARE,
                PayOrderType.TIMEOUT);
        return closeFlag ? JsonData.buildSuccess("订单关闭成功") : JsonData.buildError("关闭失败");
    }
}
